﻿using System.Windows;
using System.Windows.Interactivity;
using CardPlay.Client.ViewModels;

#if SILVERLIGHT
//#define CARDPLAY_HOOKDATACONTEXT
#endif

namespace CardPlay.Client.Behaviors
{
    public class CanvasSizingBehavior : Behavior<FrameworkElement>
    {
        protected override void OnAttached()
        {
            base.OnAttached();
            AssociatedObject.SizeChanged += OnSizeChanged;
#if CARDPLAY_HOOKDATACONTEXT
            AssociatedObject.AddDataContextChangedEventHandler(OnDataContextChanged);
#endif
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();
            AssociatedObject.SizeChanged -= OnSizeChanged;
#if CARDPLAY_HOOKDATACONTEXT
            AssociatedObject.RemoveDataContextChangedEventHandler(OnDataContextChanged);
#endif
        }

#if CARDPLAY_HOOKDATACONTEXT
        private void OnDataContextChanged(object sender, DataContextChangedEventArgs args)
        {
            if (AssociatedObject != null) UpdateSize(AssociatedObjectSize);
        }

        private Size AssociatedObjectSize
        {
            get { return new Size(AssociatedObject.ActualWidth, AssociatedObject.ActualHeight); }
        }
#endif

        private void OnSizeChanged(object sender, SizeChangedEventArgs e)
        {
            UpdateSize(e.NewSize);
        }

        private void UpdateSize(Size size)
        {
            var playingContext = AssociatedObject.DataContext as IPlayingContext;
            if (playingContext == null) return;

            playingContext.Canvas.ViewportSize = new CardPlay.Model.Primitives.Size((int)size.Width, (int)size.Height);
        }
    }
}